//
//  RegisterTableViewCell.m
//  乐清
//
//  Created by mac on 16/5/5.
//  Copyright © 2016年 Simon. All rights reserved.
//

#import "RegisterTableViewCell.h"

CGFloat registerTextFieldY = 0;

@implementation RegisterTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)registerNotification {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        [self registerNotification];
        _dataDic = [NSDictionary dictionary];
    }
    return self;
}

- (void)setLayoutDic:(NSDictionary *)layoutDic {
    // 0：自己填  3：户籍省县 4：性别  5：民族  6：报名学校
    _layoutDic = layoutDic;
    
    [self dataForDropDownView];
    
    self.infoLabel.text = _layoutDic[@"info"];
    self.fillInTextField.placeholder = _layoutDic[@"placeholder"];
    
    if ([_layoutDic[@"type"] integerValue] >= 3) {
        
        self.imgView.backgroundColor = [UIColor yellowColor];
    }
    [self setCellSubviewsFrame];
}

- (void)setCellSubviewsFrame {
    
    NSString *info = _layoutDic[@"info"];
    NSString *placeholder = _layoutDic[@"placeholder"];
    NSInteger labelWidth = (NSInteger)[info length] * kTextFont;
    NSInteger fieldWidth = (NSInteger)[placeholder length] * kTextFont;
    
    _infoLabel.frame = CGRectMake(kSpaceToSideCustom, 0, labelWidth, kCellHeight);
    
    if (self.contentView.frame.size.height <= kCellHeight * 1.5) {
        
        _fillInTextField.frame = CGRectMake(kScreenWidth - kSpaceToSideCustom - kTextFontCustom - fieldWidth, 0, fieldWidth, kCellHeight);
        
        _imgView.frame = CGRectMake(kScreenWidth - kSpaceToSideCustom - kTextFontCustom, (kCellHeight - kTextFontCustom) / 2, kTextFontCustom, kTextFontCustom);
    } else {
        
        _fillInTextField.textAlignment = NSTextAlignmentLeft;
        _fillInTextField.frame = CGRectMake(kSpaceToSideCustom, kCellHeight, kScreenWidth - kSpaceToSideCustom * 2 - kTextFontCustom, kCellHeight);
        
        _imgView.frame = CGRectMake(kScreenWidth - kSpaceToSideCustom - kTextFontCustom, kCellHeight + (kCellHeight - kTextFontCustom) / 2, kTextFontCustom, kTextFontCustom);
    }

}

- (void)dataForDropDownView {
    
    _dataDic = @{
                 @"数据" : @[@"1",@"2",@"3",@"4",@"5"]
                 };
    if ([_layoutDic[@"type"] integerValue] == 3) {
        
        _dataDic = @{
                     @"数据" : @[@"乐清市户籍",@"非乐清市户籍"]
                     };
    }
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma -mark -懒加载
@synthesize infoLabel = _infoLabel;
@synthesize fillInTextField = _fillInTextField;
@synthesize imgView = _imgView;
@synthesize dropDownView = _dropDownView;

- (UILabel *)infoLabel {
    
    if (!_infoLabel) {
        
        _infoLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        
        //        _infoLabel.tag = self.tag + 1;
        _infoLabel.textColor = [UIColor blackColor];
        _infoLabel.font = [UIFont systemFontOfSize:kTextFont];
        _infoLabel.textAlignment = NSTextAlignmentLeft;
        _infoLabel.numberOfLines = 0;
        
        [self.contentView addSubview:_infoLabel];
    }
    
    return _infoLabel;
}

- (UITextField *)fillInTextField {
    
    if (!_fillInTextField) {
        
        _fillInTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        
        //        _fillInTextField.tag = self.tag + 2;
        _fillInTextField.textColor = [UIColor blackColor];
        _fillInTextField.font = [UIFont systemFontOfSize:kTextFont];
        _fillInTextField.textAlignment = NSTextAlignmentRight;
        _fillInTextField.delegate = self;
        
        [self.contentView addSubview:_fillInTextField];
    }
    
    return _fillInTextField;
}

- (UIImageView *)imgView {
    
    if (!_imgView) {
        
        _imgView = [[UIImageView alloc] initWithFrame:CGRectZero];
        
        [self.contentView addSubview:_imgView];
    }
    
    return _imgView;
}

- (SelectView *)dropDownView {
    
    if (!_dropDownView) {
        
        _dropDownView = [[SelectView alloc] initWithFrame:CGRectZero];
        _dropDownView.hidden = YES;
        //        NSLog(@"drop super = %@", self.superview);
        [self.superview.superview addSubview:_dropDownView];
    }
    
    return _dropDownView;
}

#pragma -mark -键盘弹出与消失
//实现当键盘出现的时候计算键盘的高度大小,用于输入框显示位置
- (void)keyboardWillShow:(NSNotification*)aNotification {
    //    NSLog(@"%@ will show", [self class]);
    //    NSLog(@"transformUpBlock = %@", _transformUpBlock);
    NSDictionary *info = [aNotification userInfo];
    
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSInteger keyboardHeight = (NSInteger)kbSize.height;
    
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    CGFloat offset = registerTextFieldY + kCellHeight + keyboardHeight + kNavHeight - kScreenHeight;
    //    NSLog(@"Y = %f", registerTextFieldY);
    //    NSLog(@"cellHeight = %f", self.contentView.frame.size.height);
    //    NSLog(@"kbHeight = %ld", (long)keyboardHeight);
    //    NSLog(@"offset = %f", offset);
    if ((offset > 0)&&(!_isTransformedUp)) {
        
        self.isTransformedUp = 1;
        
        if (_transformUpBlock) {
            self.transformUpBlock(duration,offset);
        }
    }
    
}
//当键盘隐藏的时候
- (void)keyboardWillHide:(NSNotification*)aNotification {
    //    NSLog(@"%@ will hide", [self class]);
    //    NSLog(@"transformDownBlock = %@", _transformDownBlock);
    NSDictionary *info = [aNotification userInfo];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    if (_isTransformedUp) {
        if (_transformDownBlock) {
            self.transformDownBlock(duration);
            
            _isTransformedUp = 0;
        }
    }
}

#pragma -mark -UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    CGRect textFieldFrame = textField.frame;
    //    CGRect textFieldFrameInWrapperView = [self convertRect:textFieldFrame toView:self.superview];
    CGRect textFieldFrameInTableView = [self convertRect:textFieldFrame toView:self.superview.superview];
    CGRect textFieldFrameInRegisterView = [self convertRect:textFieldFrame toView:self.superview.superview.superview];
    registerTextFieldY = textFieldFrameInRegisterView.origin.y;
    
    if (_selectViewShouldRemoveBlock) {
        self.selectViewShouldRemoveBlock(1);
    }
    if ([_layoutDic[@"type"] integerValue] >= 3) {
        if (_selectViewShouldRemoveBlock) {
            self.selectViewShouldRemoveBlock(0);
        }
        _dropDownView = nil;
        
        self.dropDownView.backgroundColor = [UIColor whiteColor];
        _dropDownView.hidden = NO;
        _dropDownView.tableViewCount = 1;
        _dropDownView.cellData = [NSMutableDictionary dictionaryWithDictionary:_dataDic];
        
        if ([_dataDic allKeys].count == 1) {
            NSUInteger arrCount = ((NSArray *)[_dataDic valueForKey:@"数据"]).count;
            if (arrCount < 4) {
                if ((registerTextFieldY + kCellHeight + kCellHeight * (arrCount + 1)) < kScreenHeight) {
                    _dropDownView.frame = CGRectMake(kScreenWidth / 2, textFieldFrameInTableView.origin.y + kCellHeight, kScreenWidth / 2 - 20, kCellHeight * arrCount);
                } else {
                    _dropDownView.frame = CGRectMake(kScreenWidth / 2, textFieldFrameInTableView.origin.y - kCellHeight * arrCount, kScreenWidth / 2 - 20, kCellHeight * arrCount);
                }
            } else {
                if ((registerTextFieldY + kCellHeight + kCellHeight * 5) < kScreenHeight) {
                    _dropDownView.frame = CGRectMake(kScreenWidth / 2, textFieldFrameInTableView.origin.y + kCellHeight, kScreenWidth / 2 - 20, kCellHeight * 4);
                } else {
                    _dropDownView.frame = CGRectMake(kScreenWidth / 2, textFieldFrameInTableView.origin.y - kCellHeight * 4, kScreenWidth / 2 - 20, kCellHeight * 4);
                }
            }
        } else {
            if ((registerTextFieldY + kCellHeight + kCellHeight * 5) < kScreenHeight) {
                _dropDownView.frame = CGRectMake(kScreenWidth / 2, textFieldFrameInTableView.origin.y + kCellHeight, kScreenWidth / 2 - 20, kCellHeight * 4);
            } else {
                _dropDownView.frame = CGRectMake(kScreenWidth / 2, textFieldFrameInTableView.origin.y - kCellHeight * 4, kScreenWidth / 2 - 20, kCellHeight * 4);
            }
        }
        __weak RegisterTableViewCell *weakSelf = self;
        _dropDownView.selectFinishedBlock = ^(NSArray *fullName) {
            weakSelf.fillInTextField.text = fullName.lastObject;
            NSInteger fieldWidth = [weakSelf.fillInTextField.text length] * kTextFont;
            weakSelf.fillInTextField.frame = CGRectMake(kScreenWidth - kSpaceToSideCustom - kTextFontCustom - fieldWidth, 0, fieldWidth, kCellHeight);
            [weakSelf.dropDownView removeFromSuperview];
            
            if (weakSelf.editingEnd) {
                weakSelf.editingEnd(weakSelf.infoLabel.text, weakSelf.fillInTextField.text);
            }
        };
        
        return NO;
    }

    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
   if (self.contentView.frame.size.height <= kCellHeight * 1.5) {
       NSInteger fieldWidth = [self.fillInTextField.text length] * kTextFont;
       if (fieldWidth > (kScreenWidth - kSpaceToSideCustom * 2 - kTextFontCustom - self.infoLabel.width)) {
           fieldWidth = kScreenWidth - kSpaceToSideCustom * 2 - kTextFontCustom - self.infoLabel.width;
       }
       textField.frame = CGRectMake(kScreenWidth - kSpaceToSideCustom - kTextFontCustom - fieldWidth, 0, fieldWidth, kCellHeight);
    }
    if ([self.fillInTextField.text isEqualToString:@""]) {
        if (self.contentView.frame.size.height <= kCellHeight * 1.5) {
            textField.frame = CGRectMake(kScreenWidth - kSpaceToSideCustom - kTextFontCustom - [self.fillInTextField.placeholder length] * kTextFont, 0, [self.fillInTextField.placeholder length] * kTextFont, kCellHeight);
        }
    }
    
    if (_editingEnd) {
        self.editingEnd(_infoLabel.text, _fillInTextField.text);
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

@end
